package ch.fhnw.qualiscan.application.elements;

import ch.fhnw.qualiscan.application.components.CustomLoginForm;
import java.io.Serializable;

import ch.fhnw.qualiscan.ApplicationData;
import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.components.LoginBox;
import ch.fhnw.qualiscan.application.modals.ForgotPassword;
import ch.fhnw.qualiscan.application.models.AdminModel;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.application.models.UserModel;
import ch.fhnw.qualiscan.core.db.pojos.Language;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.db.pojos.User;
import ch.fhnw.qualiscan.core.helpers.UserSessionHelper;
import ch.fhnw.qualiscan.core.helpers.UserSession;
import ch.fhnw.qualiscan.core.libraries.ComponentLibrary;
import ch.fhnw.qualiscan.core.libraries.ModalLibrary;


import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.LoginForm.LoginEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.LoginForm;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

import eu.livotov.tpt.TPTApplication;
import eu.livotov.tpt.i18n.TM;

/**
 * 
 * @author Benjamin Groehbiel
 *
 */
@SuppressWarnings("serial")
public class LoginFormElement extends VerticalLayout implements Serializable {
	
	Label statusText = new Label("");
	public TextField username = new TextField();
	public TextField password = new TextField();
	Button loginButton = new Button(TM.get("action.login"));
	
	boolean loginCorrect = false;
	User user = null;
	
	private ModalLibrary modalLib;
	
	public SurveyUserRole invitationSurvey = null;
	public boolean updateSur = false;

	private UserModel um;
	private SurveyModel sm;
	private AdminModel am;
	
	
	
	public User u;

	
	ProgressIndicator loading = new ProgressIndicator();
	
	UserSessionHelper sessionHelper;
	ApplicationData appObject;
	public CustomLoginForm login;
	
	public LoginFormElement(LoginBox vars) {
		
		modalLib = new ModalLibrary();
		
		this.invitationSurvey = vars.invitationSurvey;
		this.updateSur = vars.updateSur;
		
		appObject = (ApplicationData) TPTApplication.getCurrentApplication().getMainWindow().getData();
		//urlLib = appObject.getUrlLib();
		buildLoginForm();
	}

	private void buildLoginForm() {
		login = new CustomLoginForm();
		login.addListener(new LoginForm.LoginListener() {
			public void onLogin(LoginEvent event) {
				login(event.getLoginParameter("username"), event.getLoginParameter("password"));
			}
		});

		// statusText style
		statusText.setStyleName("error");
		statusText.setVisible(false);
		statusText.setValue(TM.get("login.incorrect"));
		
		sessionHelper = new UserSessionHelper();
		setSpacing(true);
		
		sm = new SurveyModel();
		um = new UserModel();
		am = new AdminModel();
		
		// username
		/*
		username.focus();
		username.setInputPrompt(TM.get("user.username"));
		username.setWidth("100%");
		
		// password
		password.setSecret(true);
		password.setInputPrompt(TM.get("user.password"));
		password.setWidth("100%");
		password.setImmediate(false);
		*/
		// login button
		loginButton.addListener(new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {	
				login(username.getValue().toString(), password.getValue().toString());
			}
		});
		loginButton.setClickShortcut(KeyCode.ENTER);
		
		// progressbar
		loading.setIndeterminate(true);
		loading.setVisible(false);
		
		// forgot password
		Button forgotPassword = new Button(TM.get("login.forgot"));
		forgotPassword.setStyleName(Button.STYLE_LINK);
		forgotPassword.setIcon(Config.ICON_KEY);
		forgotPassword.addListener(new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				modalLib.openModal(new ForgotPassword());
			}
		});
		
		addComponent(login);
		//addComponent(username);
		//addComponent(password);
		//addComponent(loginButton);
		addComponent(statusText);
		addComponent(loading);
		addComponent(forgotPassword);
	
	}
	
	public void loginCorrect(User user) {
		u = user;
		
		UserSession us = new UserSession();
		us.setFirstname(u.getFirstname());
		us.setLastname(u.getLastname());
		us.setId(u.getId());
		us.setEmail(u.getEmail());
		us.setRole(u.getRole());
		sessionHelper.setUserSession(us);
		
		
		
		// if user chooses another account
		if(updateSur == true && invitationSurvey != null) {
			
			User oldUser = invitationSurvey.getUser();
			
			// correct user
			invitationSurvey.setUser(u);
			// update current sur, so that userId equals current userId
			sm.updateSur(invitationSurvey);
			
			// delete unused user
			if (oldUser.getFirstname().equals("")) {
				am.deleteUnusedUser(oldUser);
			}
			
			
			//Persist user
			u = um.getUserById(u.getId());
		}
		
		// change language
		
		
		us.setLanguage(u.getLanguage());
		
		if(!TM.getDictionary().getDefaultLanguage().equals(us.getLanguage().getLanguage())) {
			TM.getDictionary().setDefaultLanguage(us.getLanguage().getLocale());
			TPTApplication.getCurrentApplication().getMainWindow().requestRepaintAll();
		}
		
		//Change Layout
		ComponentLibrary componentLib = new ComponentLibrary();
		componentLib.userLoggedIn();
		
		if(us.getRole().getId() == Config.ADMINISTRATOR_ID) {
			//urlLib.setPage("Admin");
		} else {
			//urlLib.setPage("Dashboard");
		}
		
	}
	
	public void login(String username, String password) {
		statusText.setVisible(false);
		UserModel um = new UserModel();
		User u = um.login(username, password);
		
		if (u == null) {
			loginIncorrect();
		}
		else {
			loginCorrect(u);
		}
	}
	
	public void loginIncorrect() {
		statusText.setVisible(true);
		this.removeComponent(login);
		login = null;
		login = new CustomLoginForm();
		login.addListener(new LoginForm.LoginListener() {
			public void onLogin(LoginEvent event) {
				login(event.getLoginParameter("username"), event.getLoginParameter("password"));
			}
		});
		this.addComponent(login);
		//username.setEnabled(true);
		//password.setEnabled(true);
		//loginButton.setEnabled(true);
		//loading.setVisible(false);
	}


	public void setUsername(String email) {
		
	}
}
